{% extends "manage/layout.html" %}
{% block title %}课程管理{% endblock %}

{% block content %}
<div class="grid-2-col">
    <div class="panel">
        <div class="panel-header"><h2>新建课程 (模板)</h2></div>
        <div class="panel-body">
            <form id="form-create-course" action="/api/manage/courses/create" method="POST">
                <div class="form-group">
                    <label for="course_name">课程名称 (如: Python程序设计)</label>
                    <input type="text" id="course_name" name="name" required>
                </div>
                <div class="form-group">
                    <label for="description">课程简介</label>
                    <textarea id="description" name="description" rows="3"></textarea>
                </div>
                <div class="form-group">
                    <label for="credits">学分</label>
                    <input type="number" id="credits" name="credits" value="1.0" step="0.5" min="0">
                </div>
                <button type="submit" class="btn btn-primary btn-block">创建新课程</button>
            </form>
        </div>
    </div>

    <div class="panel">
        <div class="panel-header"><h2>我的课程</h2></div>
        <div class="panel-body">
            <ul class="item-list">
                {% for course in my_courses %}
                <li style="display: flex; justify-content: space-between; align-items: center;">
                    <span>
                        {{ course.name }}
                        {% if course.credits > 0 %}({{ course.credits }}学分){% endif %}
                    </span>
                    <div>
                        <button class="btn btn-danger btn-sm"
                                data-id="{{ course.id }}"
                                data-name="{{ course.name }}"
                                onclick="deleteCourse(this)">删除</button>
                    </div>
                </li>
                {% else %}
                <li class="placeholder">暂无课程</li>
                {% endfor %}
            </ul>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', () => {
        // 绑定创建课程表单
        const formCreateCourse = document.getElementById('form-create-course');
        if (formCreateCourse) {
            formCreateCourse.onsubmit = e => handleFormSubmit(e);
        }
    });

    // 删除课程的 JS
    async function deleteCourse(button) {
        const courseId = button.dataset.id;
        const courseName = button.dataset.name;
        
        if (!confirm(`确定要删除课程 "${courseName}" 吗？\n警告：这将同时删除该课程的所有文件和课堂关联！`)) {
            return;
        }

        const data = await apiRequest(`/api/manage/courses/${courseId}`, 'DELETE');
        if(data) {
            alert(data.message || '删除成功！');
            location.reload();
        }
    }
</script>
{% endblock %}